package com.ruoyi.web.controller.api;

import com.ruoyi.base.domain.BaseAlternateAirport;
import com.ruoyi.base.domain.BaseMainAirport;
import com.ruoyi.base.domain.BaseMeeting;
import com.ruoyi.base.service.IBaseAlternateAirportService;
import com.ruoyi.base.service.IBaseMainAirportService;
import com.ruoyi.base.service.IBaseMeetingService;
import com.ruoyi.cems.domain.*;
import com.ruoyi.cems.domain.dto.BmsEVCContactResponse;
import com.ruoyi.cems.domain.dto.BmsEmergencyVariableControlResponse;
import com.ruoyi.cems.domain.dto.EmergencyDuty;
import com.ruoyi.cems.domain.dto.TaskProgressDTO;
import com.ruoyi.cems.service.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@Api(description="试飞大屏接口")
@RestController
@RequestMapping("/api/sfdp")
public class SFDPController extends BaseController {

    @Autowired
    private IBaseMainAirportService baseMainAirportService;

    @Autowired
    private IBaseAlternateAirportService baseAlternateAirportService;

    @Autowired
    private IBmsEmergencyVariableControlService bmsEmergencyVariableControlService;

    @Autowired
    private IBmsEVCContactService bmsEVCContactService;

    @Autowired
    private IBmsEmergencyNoticeService bmsEmergencyNoticeService;
    @Autowired
    private IBmsWorkChecklistsService bmsWorkChecklistsService;

    @Autowired
    private IBaseMeetingService baseMeetingService;

    @Value("${evc.template.message}")
    private String messageTemplate;

    @Value("${api.sfdp.groups}")
    private String groups;

    @Value("${api.sfdp.mergeGroup}")
    private String mergeGroup;

    ///api/sfdp/getAirports
    @ApiOperation("获取主机场和备降机场信息")
    @GetMapping("/getAirports")
    public AjaxResult getAirportInfo() {
        Map<String ,Object> map  = new HashMap<String,Object>();
        List<BaseMainAirport> mainAirportList = baseMainAirportService.selectBaseMainAirportList();
        List<BaseAlternateAirport> alternateAirportsList =  baseAlternateAirportService.selectBaseAlternateAirportList(new BaseAlternateAirport());
        map.put("mainAirportList",mainAirportList);
        map.put("alternateAirportsList",alternateAirportsList);
        return success(map);
    }


    @ApiOperation("应急值班电话")
    @GetMapping("/getEmergencyDuty")
    public AjaxResult getEmergencyDutyInfo() {
        BaseMeeting baseMeeting = new BaseMeeting();
        baseMeeting.setType(2);
        List<EmergencyDuty> emergencyDutyList = baseMeetingService.selectEmergencyDutyList(baseMeeting);
        return success(emergencyDutyList);
    }


    @ApiOperation("获取任务进度")
    @GetMapping("/getTaskProgress")
    public AjaxResult getTaskProgress(@ApiParam(value = "任务单号", required = true) @RequestParam String taskNo) {
        if (taskNo == null || taskNo.trim().isEmpty()) {
            return error("任务单号不能为空");
        }else {
            BmsEmergencyVariableControlResponse response = new BmsEmergencyVariableControlResponse();
            //通过taskNo获取变量控制表
            BmsEmergencyVariableControl bvc = bmsEmergencyVariableControlService.selectBmsEmergencyVariableControlByTaskNo(taskNo);
            if(bvc == null){
                return error("未找到任务单号："+taskNo+"相关任务进度信息");
            }
            Map<String, Object> params =  new HashMap<>();
            params.put("taskNo",bvc.getTaskNo());
            params.put("taskName",bvc.getTaskName());
            //获取通知信息
            BmsEmergencyNotice bmsEmergencyNotice = new BmsEmergencyNotice();
            bmsEmergencyNotice.setVcId(bvc.getID());
            bmsEmergencyNotice.setStatus("StartUp");
            bmsEmergencyNotice.setManager(true);
            List<BmsEmergencyNotice> bmsEmergencyNotices = bmsEmergencyNoticeService.selectBmsEmergencyNoticeList(bmsEmergencyNotice);
            if (Objects.nonNull(bmsEmergencyNotices) && !bmsEmergencyNotices.isEmpty()) {
                bmsEmergencyNotice = bmsEmergencyNotices.get(0);
                params.put("startTime", bmsEmergencyNotice.getStartTime());
                List<TaskProgressDTO> taskProgressDTOList = bmsWorkChecklistsService.getTaskProgress(bmsEmergencyNotice.getTaskForm(),groups);

                String[] groupStr = mergeGroup.split("&");
                for (String groupName : groupStr){
                    List<TaskProgressDTO>  taskProgressList = bmsWorkChecklistsService.getTaskProgress(bmsEmergencyNotice.getTaskForm(),groupName);
                    // 使用流操作计算总任务数和已完成任务数
                    int total = taskProgressList.stream().mapToInt(TaskProgressDTO::getTotal).sum();
                    int finished = taskProgressList.stream().mapToInt(TaskProgressDTO::getFinished).sum();

                    // 创建并设置 TaskProgressDTO 对象
                    TaskProgressDTO taskProgress = new TaskProgressDTO();
                    taskProgress.setGroupName(groupName);
                    taskProgress.setTotal(total);
                    taskProgress.setFinished(finished);

                    // 添加到任务进度列表
                    taskProgressDTOList.add(taskProgress);
                }
                params.put("taskProgressList", taskProgressDTOList);
                return success(params);
            }else{
                return error("未找到任务单号："+taskNo+"的应急通知");
            }
        }
    }


    @ApiOperation("获取应急信息")
    @GetMapping("/getEmergencyInfo")
    public AjaxResult getEmergencyInfo(@ApiParam(value = "任务单号", required = true) @RequestParam String taskNo) {
        if (taskNo == null || taskNo.trim().isEmpty()) {
            return error("任务单号不能为空");
        }else {
            BmsEmergencyVariableControlResponse response = new BmsEmergencyVariableControlResponse();
            BmsEmergencyVariableControl bvc = bmsEmergencyVariableControlService.selectBmsEmergencyVariableControlByTaskNo(taskNo);
            if(bvc == null){
                return error("未找到任务单号："+taskNo+"相关应急信息");
            }
            Map<String, BmsWorkChecklists> workChecklistsMap = new HashMap<>();
            //获取最新一条应急通知单
            BmsEmergencyNotice bmsEmergencyNotice = new BmsEmergencyNotice();
            bmsEmergencyNotice.setVcId(bvc.getID());
            bmsEmergencyNotice.setStatus("StartUp");
            bmsEmergencyNotice.setManager(true);
            List<BmsEmergencyNotice> bmsEmergencyNotices = bmsEmergencyNoticeService.selectBmsEmergencyNoticeList(bmsEmergencyNotice);
            if (Objects.nonNull(bmsEmergencyNotices) && !bmsEmergencyNotices.isEmpty()) {
                bmsEmergencyNotice = bmsEmergencyNotices.get(0);
                //赋值给Response
                response.setTaskNo(bmsEmergencyNotice.getTaskNo());
                response.setAirport(bmsEmergencyNotice.getAirport());
                response.setCantry(bmsEmergencyNotice.getCantry());
                response.setView(bmsEmergencyNotice.getView());
                response.setResponseLevel(bmsEmergencyNotice.getResponseLevel());
                response.setActionLevel(bmsEmergencyNotice.getActionLevel());
                response.setStartTime(bmsEmergencyNotice.getStartTime());
                String message = String.format(messageTemplate, bmsEmergencyNotice.getAirport(), bmsEmergencyNotice.getCantry(), bmsEmergencyNotice.getTaksContent(),bmsEmergencyNotice.getView(), bmsEmergencyNotice.getResponseLevel(), bmsEmergencyNotice.getTaksContent());
                response.setMessage(message);
                List<BmsWorkChecklists> bmsWorkChecklists = bmsWorkChecklistsService.selectBmsWorkChecklistsByEnID(bmsEmergencyNotice.getID());
                if (Objects.nonNull(bmsWorkChecklists) && !bmsWorkChecklists.isEmpty()) {
                    bmsWorkChecklists.forEach(bmsWorkChecklist -> {
                        workChecklistsMap.put(bmsWorkChecklist.getJobNumber()+bmsWorkChecklist.getPosition(), bmsWorkChecklist);
                    });
                }
            }
            //联络人信息
            List<BmsEVCContact> bmsEVCContacts = bmsEVCContactService.selectBmsEVCContactListByparentId(bvc.getID(),"command");
            List<BmsEVCContactResponse> bmsEVCContactResponses = new ArrayList<>();
            if (Objects.nonNull(bmsEVCContacts) && !bmsEVCContacts.isEmpty()) {
                for (BmsEVCContact bmsEVCContact : bmsEVCContacts) {
                    BmsEVCContactResponse bmsEVCContactResponse = new BmsEVCContactResponse();
                    bmsEVCContactResponse.setName(bmsEVCContact.getName());
                    bmsEVCContactResponse.setTel(bmsEVCContact.getTel());
                    bmsEVCContactResponse.setRoleName(bmsEVCContact.getPositionName());
                    bmsEVCContactResponse.setDuty(bmsEVCContact.getDuty());
                    bmsEVCContactResponse.setJobNumber(bmsEVCContact.getJobNumber());
                    if (workChecklistsMap.containsKey(bmsEVCContact.getJobNumber()+bmsEVCContact.getPosition())) {
                        bmsEVCContactResponse.setDuty(workChecklistsMap.get(bmsEVCContact.getJobNumber()+bmsEVCContact.getPosition()).getDuty());
                    }
                    bmsEVCContactResponses.add(bmsEVCContactResponse);
                }
                response.setEvcContacts(bmsEVCContactResponses);
            }
            return success(response);
        }
    }
}
